package com.qjq.glasses_shopping.security;


import com.qjq.glasses_shopping.pojo.Admin;
import com.qjq.glasses_shopping.pojo.Permission;
import com.qjq.glasses_shopping.service.AdminService;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

//认证和授权逻辑
@Service
public class MyUserDetailService implements UserDetailsService {
    @Resource
    private AdminService adminService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.认证逻辑
        Admin admin = adminService.findByAdminName(username);
        if (admin == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        //2.授权逻辑
        List<Permission> permissions=adminService.findAllPermission(username);
        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        if (permissions.get(0) != null){
            for (Permission permission : permissions) {
                grantedAuthorities.add(new SimpleGrantedAuthority(permission.getUrl()));
            }
        }
        //3.封装为userDetail对象
        UserDetails userDetails = User.withUsername(admin.getUsername())
                .password(admin.getPassword())
                .authorities(grantedAuthorities)
                .build();

        //4.返回userdetail对象
        return userDetails;
    }
}
